package com.rankeiot.core.anno.aspect;

import com.rankeiot.core.exception.BusinessException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.CodeSignature;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.MethodResolver;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;


public abstract class AbstractExpressionAspect {
    static ExpressionParser parser = new SpelExpressionParser();
    protected  <T> T executeExpression(JoinPoint point,StandardEvaluationContext ctx, String expressionStr){
        //StandardEvaluationContext ctx = new StandardEvaluationContext();
        Expression expression = parser.parseExpression(expressionStr);
        CodeSignature signature = (CodeSignature) point.getSignature();
        String[] params = signature.getParameterNames();
        Object[] args = point.getArgs();
        for (int i = 0; i < params.length; i++) {
            ctx.setVariable(params[i], args[i]);
        }

       return (T)expression.getValue(ctx);
    }
    protected void throwBusinessException(JoinPoint point,String message) throws BusinessException{
        Signature signature =  point.getSignature();
        StackTraceElement stte=new StackTraceElement(signature.getDeclaringTypeName(),signature.getName(),  signature.getDeclaringType().getSimpleName()+".java",-1);
        BusinessException be= new BusinessException(message);
        be.setStackTrace(new StackTraceElement[]{stte});
        throw be;
    }
}
